<template>
  <div class="box">
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
    >
      <el-form-item label="登陆账号" prop="userName">
        <el-input v-model="ruleForm.userName" />
      </el-form-item>
      <el-form-item label="登陆密码" prop="userPass">
        <el-input v-model="ruleForm.userPass" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          登陆
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { adminLogin } from "../api/api";

const router = useRouter();

interface RuleForm {
  userName: string;
  userPass: string;
}

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  userName: "",
  userPass: "",
});

const locationOptions = ["Home", "Company", "School"];

const rules = reactive<FormRules<RuleForm>>({
  userName: [
    { required: true, message: "请输入登陆账号", trigger: "blur" },
    { min: 3, max: 10, message: "账号长度为3到10位", trigger: "blur" },
  ],
  userPass: [
    { required: true, message: "请输入登陆密码", trigger: "blur" },
    { min: 3, max: 10, message: "密码长度为3到10位", trigger: "blur" },
  ],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      adminLogin(ruleForm).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("登陆成功");
          let user = res.data.data;
          let token = user.token;
          sessionStorage.setItem("token", token);
          sessionStorage.setItem("user", JSON.stringify(user));

          router.push("/home");
        } else {
          ElMessage.error("登陆失败");
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}));
</script>
